package com.github.authcloud.server.configure.filter.zuul;

import com.github.authcloud.common.NoRequiresLoginMapping;
import com.github.authcloud.common.RequiresRolePermissionMapping;
import com.github.authcloud.server.configure.checker.UserAuthRolePermission;
import com.github.authcloud.server.configure.AuthRolePermissionLocalCache;
import com.github.authcloud.server.configure.properties.AuthCommonProperties;
import com.github.authcloud.server.configure.utils.AuthRolePermissionMatchUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author : zhaoxuan
 * @version : 1.0
 * @date : 2021/8/22 14:47
 * @description : RolesPermissionsFilter
 */
public class ZuulAuthRolePermissionFilter extends ZuulFilter{

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private UserAuthRolePermission userAuthRolePermission;

    @Resource
    private AuthCommonProperties authCommonProperties;

    @Override
    public String filterType() {
        return FilterConstants.ROUTE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.RIBBON_ROUTING_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        String uri =(String)context.get("requestURI");
        if (!authCommonProperties.getNotInterApiPrefix().isEmpty()) {
            return authCommonProperties.getNotInterApiPrefix().stream()
                    .map(notInterApiPreFix -> notInterApiPreFix.replaceAll("\\*", ""))
                    .noneMatch(uri::startsWith);
        }
        if (!authCommonProperties.getInterApiPrefix().isEmpty()) {
            return authCommonProperties.getInterApiPrefix().stream()
                    .map(interApiPrefix -> interApiPrefix.replaceAll("\\*", ""))
                    .anyMatch(uri::startsWith);
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String uri = (String)context.get("requestURI");
        String serviceName =(String)context.get("serviceId");
        String method = request.getMethod();
        List<NoRequiresLoginMapping> noRequiresLoginMappings = AuthRolePermissionLocalCache.getNoLoginMapping(serviceName);
        boolean inNoLoginMappings = AuthRolePermissionMatchUtil.isInNoLoginMappings(uri, method, noRequiresLoginMappings);
        if (!inNoLoginMappings && !userAuthRolePermission.isLogin()) {
            String message = "access this api required authentication";
            throw new ZuulException(message, 401, message);
        }
        List<RequiresRolePermissionMapping> requiresRolePermissionMappings = AuthRolePermissionLocalCache.getRolesPermissionMapping(serviceName);
        RequiresRolePermissionMapping rolesPermission = AuthRolePermissionMatchUtil.getRequiresRolesPermissionsMapping(uri, method, requiresRolePermissionMappings);
        if (rolesPermission == null) {
            return null;
        }
        boolean roleCheckIsPass = AuthRolePermissionMatchUtil.checkRoles(userAuthRolePermission.getRoles(), rolesPermission.getRoles(), rolesPermission.getRolesLogical());
        if (!roleCheckIsPass) {
            String message = "access this api required roles " + rolesPermission.getRoles().toString();
            throw new ZuulException(message, 403, message);
        }
        boolean permissionsCheckIsPass = AuthRolePermissionMatchUtil.checkPermissions(userAuthRolePermission.getPermissions(), rolesPermission.getPermissions(), rolesPermission.getPermissionsLogical());
        if (!permissionsCheckIsPass) {
            String message = "access this api required permissions " + rolesPermission.getPermissions().toString();
            throw new ZuulException(message, 403, message);
        }
        return null;
    }
}
